package com.itheima.web.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.SysLog;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/system/sysLog")
public class SysLogServlet extends BaseServlet {
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int size = 10;
        if (StringUtils.isNotBlank(request.getParameter("currentPage"))) {
            page = Integer.parseInt(request.getParameter("currentPage"));
        }
        if (StringUtils.isNotBlank(request.getParameter("pageSize"))) {
            size = Integer.parseInt(request.getParameter("pageSize"));
        }
        PageInfo pageInfo = sysLogService.findAll(page, size);
        request.setAttribute("operation", "list");
        request.setAttribute("page", pageInfo);
        // TODO: 2020/9/9
        request.getRequestDispatcher("/pages/system/syslog-list.jsp").forward(request, response);
    }

    public void report(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("用户访问日志.xlsx".getBytes(), "iso-8859-1");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        //生成报告文件,然后传递到前端页面
        sysLogService.getReport(response.getOutputStream());
    }


    public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String searchTime = request.getParameter("searchTime");
        String size = request.getParameter("pageSize");
        String page = request.getParameter("currentPage");
        PageInfo<SysLog> pageInfo = sysLogService.search(searchTime, page, size);
        request.setAttribute("page", pageInfo);
        request.setAttribute("searchTime", searchTime);
        request.setAttribute("operation", "search");
        // TODO: 2020/9/9  
        request.getRequestDispatcher("/pages/system/syslog-list.jsp").forward(request, response);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String ids = request.getParameter("ids");
        String[] idArr = ids.split(",");
        sysLogService.delete(idArr);
        response.sendRedirect(request.getContextPath() + "/system/sysLog?operation=list");
    }
}
